package com.cc.stock.web;

import com.cc.stock.dto.Result;
import com.cc.stock.entity.Delegate;
import com.cc.stock.entity.DelegateInput;
import com.cc.stock.entity.User;
import com.cc.stock.service.DelegateService;
import com.cc.stock.util.CheckLogin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/delegate")
public class DelegateController {

    @Autowired
    private DelegateService delegateService;

//    CheckLogin checkLogin = new CheckLogin();
    //买卖交易的委托请求
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ResponseBody
    public Result<String> add(@RequestBody DelegateInput delegate, HttpSession session){
//        checkLogin.checkLogin(session);
//        User user;
        User user = (User) session.getAttribute("user");
        if (user == null){
            return new Result<>(-1, "未登录");
        }
        int userId = user.getId();
        try {
            if (delegate.getNum() <= 0 || delegate.getPrice() <= 0) {
                return new Result<>(201, "字段不合法");
            }
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            delegateService.addDelegate(userId,delegate.getStockId(),delegate.getPrice()
                ,delegate.getNum(),delegate.isType(),format.format(new Date()));
            return new Result<String>(200,"委托成功！");
        }catch (Exception e){
            e.printStackTrace();
            return new Result<String>(201, e.toString() + e.getMessage());
        }
    }

//委托表
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    @ResponseBody
    public Result<List> list(HttpSession session){
        User user = (User) session.getAttribute("user");
        if (user == null){
            return new Result<>(-1, "未登录");
        }
        int userId = user.getId();
        try {
            return new Result<List>("委托列表", delegateService.findAllDelegate(userId));
        }catch (Exception e){
            e.printStackTrace();
            return new Result<>(201, e.toString() + e.getMessage());
        }
    }

//取消委托
    @RequestMapping(value = "/cancel",method = RequestMethod.GET)
    @ResponseBody
    public Result<String> cancel(Integer delegateId,HttpSession session){
        User user = (User) session.getAttribute("user");
        if (user == null){
            return new Result<>(-1, "未登录");
        }

        if (delegateId == null) {
            return new Result<>(201, "Param delegateId is null");
        }

        try {
            delegateService.cancelDelegate(delegateId);
            return new Result<>(200, "取消委托");
        }catch (Exception e){
            e.printStackTrace();
            return new Result<>(201, e.toString() + e.getMessage());
        }
    }
}
